﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace ElemenTable
{
    public partial class MainForm : Form
    {
        private TableManager ptemanager;
        private Button[] elembuttons;
        internal ElementForm infobox;

        public MainForm()
        {
            InitializeComponent();
            ptemanager = new TableManager();
            ptemanager.LoadTable();
            InitializeTable();
        }

        #region MainForm methods

        private void MainForm_Load(object sender, EventArgs e)
        {
            conLangDe.Checked = false;
            conLangEn.Checked = false;
            string cult = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
            if (cult == "de")
                conLangDe.Checked = true;
            else conLangEn.Checked = true;
            statAbout.Text = "v." + this.ProductVersion.Substring(0,5) + statAbout.Text;
        }

        private void InitializeTable()
        {
            elembuttons = new Button[ptemanager.TableElements.Count];
            for (int i = 0; i < elembuttons.Length; i++)
            {
                string istring = i.ToString("000"); 
                ChemElement elem = ptemanager.TableElements[i];
                elembuttons[i] = new Button();
                elembuttons[i].Dock = DockStyle.Fill;
                elembuttons[i].FlatAppearance.BorderSize = 3;
                elembuttons[i].FlatStyle = FlatStyle.Flat;
                elembuttons[i].Font = new Font("Consolas", 9.75F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(0)));
                elembuttons[i].BackColor = ptemanager.GroupColor[elem.GroupName];
                conViewGroups.Checked = true;
                elembuttons[i].Location = new Point(27, 189);
                elembuttons[i].Margin = new Padding(2);
                elembuttons[i].Name = istring + "button";
                elembuttons[i].Size = new Size(45, 50);
                elembuttons[i].TabStop = true;
                elembuttons[i].TabIndex = elem.Number;
                elembuttons[i].Text = String.Format("{0}\n{1}",elem.Number,elem.Symbol);
                this.quickinfo.SetToolTip(elembuttons[i], elem.Name);
                elembuttons[i].Click += elem_Click;
                elembuttons[i].GotFocus += elem_Focus;
                int col = elem.GroupNumber;
                int row = elem.PeriodNumber;
                if (elem.Number >= 57 && elem.Number <= 71)
                { row += 3; col = -53 + elem.Number; }
                if (elem.Number >= 89 && elem.Number <= 103)
                { row += 3; col = -85 + elem.Number; }
                layoutTable.Controls.Add(elembuttons[i], col, row);
            }
            layoutTable.Controls.Add(note_Label("*"), 3, 6);
            layoutTable.Controls.Add(note_Label("*"), 3, 9);
            layoutTable.Controls.Add(note_Label("**"), 3, 7);
            layoutTable.Controls.Add(note_Label("**"), 3, 10);
            //Help button
            Button helpbutton = new Button();
            helpbutton.Font = new Font("Consolas", 9.75F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(0)));
            helpbutton.Size = new Size(30, 30);
            helpbutton.Anchor = AnchorStyles.Top & AnchorStyles.Bottom & AnchorStyles.Left & AnchorStyles.Right;
            helpbutton.Text = "?";
            helpbutton.Click += conExplain_Click;
            layoutTable.Controls.Add(helpbutton, 1, 10);
        }

        private Label note_Label(string stars)
        {
            return new Label() { Text = stars, Dock = DockStyle.Fill, Size = new Size(43,54), TextAlign = ContentAlignment.MiddleCenter,
                Font = new Font("Consolas", 15) };
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            this.Focus();
        }

        #endregion

        #region Element interaction

        private void elem_Click(object sender, EventArgs e)
        {
            if (infobox != null) { infobox.Close(); infobox = null; }
            int sendernum = int.Parse(((Button)sender).Name.Substring(0, 3));
            ChemElement elem = ptemanager.TableElements[sendernum];
            infobox = new ElementForm(ptemanager, elem);
            infobox.Show(this);
        }

        private void elem_Focus(object sender, EventArgs e)
        {
            int sendernum = int.Parse(((Button)sender).Name.Substring(0, 3));
            ChemElement elem = ptemanager.TableElements[sendernum];
            statInfo.Text = String.Format("{0} ; {1} ; {2}", elem.Number, elem.Symbol, elem.Name);
        }

        private void conExplain_Click(object sender, EventArgs e)
        {
            Dictionary<string, Color> current = ptemanager.GroupColor;
            if (conViewState.Checked) current = ptemanager.StateColor;
            else if (conViewType.Checked) current = ptemanager.TypeColor;
            ExplanationForm exform = new ExplanationForm(current);
            exform.ShowDialog();
        }

        private void quickinfo_Popup(object sender, PopupEventArgs e)
        {
            ((Button)e.AssociatedControl).Focus();
        }

        #endregion

        #region Menu methods

        private void conAbout_Click(object sender, EventArgs e)
        {
            InfoWindow info = new InfoWindow(); 
            info.ShowDialog();
        }

        private void conViews_Click(object sender, EventArgs e)
        {
            if (!((ToolStripMenuItem)sender).Checked)
            {
                conViewGroups.Checked = false;
                conViewState.Checked = false;
                conViewType.Checked = false;
                int num = 0;
                if (sender == conViewState) num = 1;
                else if (sender == conViewType) num = 2;
                ptemanager.SetColorDesign(num);
                ((ToolStripMenuItem)sender).Checked = true;
                for (int i = 0; i < elembuttons.Length; i++)
                {
                    string istring = i.ToString("000");
                    ChemElement elem = ptemanager.TableElements[i];
                    elembuttons[i].BackColor = ptemanager.GetCurrentColor(elem);
                }
            }
        }

        private void conSearch_Click(object sender, EventArgs e)
        {
            SearchForm search = new SearchForm(ptemanager);
            search.ShowDialog(this);
        }

        private void conPrint_Click(object sender, EventArgs e)
        {
            mainmenu.Focus();
            Dictionary<string, Color> current = ptemanager.GroupColor;
            if (conViewState.Checked) current = ptemanager.StateColor;
            else if (conViewType.Checked) current = ptemanager.TypeColor;
            ExplanationForm exform = new ExplanationForm(current);
            exform.Show();
            exform.Hide();
            Bitmap exbox = new Bitmap(exform.tlpElements.Width, exform.tlpElements.Height);
            exform.tlpElements.DrawToBitmap(exbox, new Rectangle(0,0, exbox.Width, exbox.Height));
            Bitmap bmp = new Bitmap(layoutTable.Width, layoutTable.Height);
            layoutTable.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
            Graphics g = Graphics.FromImage(bmp);
            g.DrawImage(exbox, 200, 30);
            g.FillRectangle(new SolidBrush(Color.White), new Rectangle(35, 490, 30, 30));
            g.Dispose();
            Bluegrams.BluePrintBmp.PrintBmp(bmp, "ElemenTable - " + Properties.Resources.title_print);
            exbox.Dispose();
            bmp.Dispose();
        }

        private void conExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region Set Language

        private void conLangEn_Click(object sender, EventArgs e)
        {
            change_Culture(new System.Globalization.CultureInfo("en"));
        }

        private void conLangDe_Click(object sender, EventArgs e)
        {
            change_Culture(new System.Globalization.CultureInfo("de"));
        }

        private void change_Culture(System.Globalization.CultureInfo culture)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
            System.Threading.Thread.CurrentThread.CurrentCulture = culture;
            bool opened = false;
            if (infobox != null && infobox.Visible) { infobox.Close(); infobox = null; opened = true; }
            ComponentResourceManager resources = new ComponentResourceManager(typeof(MainForm));
            resources.ApplyResources(this, "$this");
            apply_Control(resources, this.Controls);
            ptemanager = new TableManager();
            ptemanager.LoadTable();
            for (int i = 0; i < elembuttons.Length; i++)
            {
                ChemElement elem = ptemanager.TableElements[i];
                elembuttons[i].Text = String.Format("{0}\n{1}", elem.Number, elem.Symbol);
                this.quickinfo.SetToolTip(elembuttons[i], elem.Name);
            }
            MainForm_Load(null, null);
           if (opened) elem_Click(this.ActiveControl, null);
        }

        private void apply_Control(ComponentResourceManager resources, Control.ControlCollection ctls)
        {
            foreach (Control con in ctls)
            {
                if (con is ToolStrip)
                {
                    apply_ToolStrip(resources, ((ToolStrip)con).Items);
                }
                resources.ApplyResources(con, con.Name);
                apply_Control(resources, con.Controls);
            }
        }

        private void apply_ToolStrip(ComponentResourceManager resources, ToolStripItemCollection itms)
        {
            foreach (ToolStripItem it in itms)
            {
                resources.ApplyResources(it, it.Name);
                if (it is ToolStripMenuItem)
                {
                    ToolStripDropDown drop = ((ToolStripMenuItem)it).DropDown;
                    if (drop is ContextMenuStrip)
                    {
                        ContextMenuStrip contxt = (ContextMenuStrip)drop;
                        resources.ApplyResources(contxt, contxt.Name);
                        apply_ToolStrip(resources, contxt.Items);
                    }
                }
            }
        }

        #endregion
    }
}
